package com.example.mydownloader

import android.util.Base64
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.mydownloader.config.globalConfig.UrlConfig
import com.example.mydownloader.data.model.inputdata.LoggedInUser
import com.example.mydownloader.data.model.inputdata.ResponseTemplate
import com.example.mydownloader.data.model.outputdata.LoginData
import com.example.mydownloader.myconst.ResponseMessage
import com.example.mydownloader.myconst.TransmissionData
import com.example.mydownloader.mymodule.encrypt.AESCryptUtil
import com.example.mydownloader.mymodule.gson.GsonUtil
import com.example.mydownloader.mymodule.http.HttpUtil
import com.example.mydownloader.mymodule.log.LogUtil
import com.example.mydownloader.mymodule.sharedpreferences.SPUtil
import org.junit.Before
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters

/**
 * Instrumented test, which will execute on an Android device.
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
@RunWith(AndroidJUnit4::class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ExampleInstrumentedTest {

    var loginData: LoginData? = null

    @Before
    fun init() {
        loginData = LoginData("Wallace1", "lwl123456!")
        UrlConfig.preRequestUrl =
            "http://10.10.122.120:8080/downloadserver/api/preRequest/preRequest"
//        UrlConfig.preRequestUrl = "http://192.168.0.156:8080/downloadserver/api/preRequest/preRequest"
        UrlConfig.loginUrl = "http://10.10.122.120:8080/downloadserver/api/login/login"
//        UrlConfig.loginUrl = "http://192.168.0.156:8080/downloadserver/api/login/login"
    }

    @Test
    fun loginTest() {
        // 登录预请求
        val preRequest = HttpUtil.createGetRequest(
            UrlConfig.preRequestUrl, null, null
        )
        val preResponse = HttpUtil.okHttpClient.newCall(preRequest).execute()
        val preResult = preResponse.body!!.string()
        LogUtil.d("preResponse = $preResult")
        var responseTemplate =
            GsonUtil.toAny(preResult, ResponseTemplate::class.java)
        if (responseTemplate == null) {
            LogUtil.e("Login failed Cause by pre-request failed")
        } else {
            if (responseTemplate.message == ResponseMessage.Success.SESSION_CREATED) {
                val publicKeyString = responseTemplate.data as String
                SPUtil.setString(TransmissionData.RSA_PUBLIC_KEY, publicKeyString)
                val aesKey = AESCryptUtil.generateKey()
                val securityKey = Base64.encode(aesKey.key, Base64.NO_WRAP)
                val iv = Base64.encode(aesKey.iv, Base64.NO_WRAP)
                SPUtil.setString(TransmissionData.AES_KEY, securityKey.toString(Charsets.UTF_8))
                SPUtil.setString(TransmissionData.AES_IV, iv.toString(Charsets.UTF_8))
            }
            val cookies = preResponse.headers("Set-Cookie")
            val session = cookies[0]
            val sessionId = session.substring(0, session.indexOf(";"))
            // 登录请求
            val loginResult = HttpUtil.postJson(
                url = UrlConfig.loginUrl,
                data = loginData,
                headers = hashMapOf(
                    "Cookie" to (sessionId)
                )
            )
            LogUtil.d("loginResult = $loginResult")
            responseTemplate =
                GsonUtil.toAny(loginResult, ResponseTemplate::class.java)
            val loggedInUser =
                GsonUtil.toAny(responseTemplate?.data, LoggedInUser::class.java)
            assert(loggedInUser!!.displayName == "威力")
        }
    }
}